#include "LPC11XX.h"
#include "adc.h"
#include "bitops.h"

void adc_init(void)
{
  //1. 启用IOCONFIG时钟
  setbit(LPC_SYSCON->SYSAHBCLKCTRL, 16);

  //2.1 将PIO0_11配置为模拟输入通道AD0
  setbits(LPC_IOCON->R_PIO0_11, 0, 2, 2);
  clrbit(LPC_IOCON->R_PIO0_11, 7);
  
  //2.2 将PIO1_2配置为模拟输入通道AD3
  setbits(LPC_IOCON->R_PIO1_2, 0, 2, 2);
  clrbit(LPC_IOCON->R_PIO1_2, 7);

  //3. 启用ADC模块
  setbit(LPC_SYSCON->SYSAHBCLKCTRL, 13);
  
  //4. ADC上电
	clrbit(LPC_SYSCON->PDRUNCFG, 4);
  
  //5. 设置分频系数，ADC时钟频率需要小于等于4.5MHz，APB频率48MHz，需要12分频
  setbits(LPC_ADC->CR, 8, 15, (12 - 1));
}

int adc_value(int channel)
{
  int value;
  
  //选择通道
  setbit(LPC_ADC->CR, channel);
  
  //开始转换
	setbits(LPC_ADC->CR, 24, 26, 1);

  //等待转换完成
  while(chkbit(LPC_ADC->DR[channel], 31) == 0);
  
  value = (LPC_ADC->DR[channel] >> 6) & 0x3ff;
  
  //清除通道选择，并停止转换
  setbits(LPC_ADC->CR, 24, 26, 0);
  clrbit(LPC_ADC->CR, channel);
  
  return value;
}
